package com.ebupt.migu.music.system.entity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * @author admin
 */
public class MenuBuilder implements Serializable {

    /**
     * 两层循环实现建树
     *
     * @param treeNodes 传入的树节点列表
     * @return
     */
    public static List<SysMenu> bulid(List<SysMenu> treeNodes) {

        List<SysMenu> trees = new ArrayList<>();

        for (SysMenu treeNode : treeNodes) {

            if ("0".equals(treeNode.getParentId())) {
                trees.add(treeNode);
            }

            for (SysMenu it : treeNodes) {
                if (it.getParentId().equals(treeNode.getId())) {
                    if (treeNode.getChildren() == null) {
                        treeNode.setChildren(new ArrayList<>());
                    }
                    treeNode.getChildren().add(it);
                }
            }
        }
        return trees;
    }

    /**
     * 使用递归方法建树
     *
     * @param treeNodes
     * @return
     */
    public static List<SysMenu> buildByRecursive(List<SysMenu> treeNodes) {
        List<SysMenu> trees = new ArrayList<>();
        for (SysMenu treeNode : treeNodes) {
            if ("0".equals(treeNode.getParentId())) {
                trees.add(findChildren(treeNode, treeNodes));
            }
        }
        return trees;
    }

    /**
     * 递归查找子节点
     *
     * @param treeNodes
     * @return
     */
    public static SysMenu findChildren(SysMenu treeNode, List<SysMenu> treeNodes) {
        for (SysMenu it : treeNodes) {
            if (treeNode.getId().equals(it.getParentId())) {
                if (treeNode.getChildren() == null) {
                    treeNode.setChildren(new ArrayList<>());
                }
                treeNode.getChildren().add(findChildren(it, treeNodes));
            }
        }
        return treeNode;
    }


    public static List<SysMenu> buildByRecursiveForLogin(List<SysMenu> treeNodes) {
        List<SysMenu> trees = new ArrayList<>();

        for (SysMenu treeNode : treeNodes) {
            if ("0".equals(treeNode.getParentId())) {
                return findChildren(treeNode, treeNodes).getChildren();
            }
        }

// TODO : 补充查询pid为0的菜单对应的ID【替换掉下面代码中写死的10】，作为二级菜单的筛选条件
        for (SysMenu treeNode : treeNodes) {
            if ("10".equals(treeNode.getParentId())) {
                trees.add(findChildren(treeNode, treeNodes));
            }
        }
        return trees;
    }
}